import SocketServer
import os
import logging.config

import parse_config
import sync_file

class MyTCPHandler(SocketServer.StreamRequestHandler):
    def handle(self):
        size = int(self.rfile.read(8))
        if size > 2**24:
            self.wfile.write('DENY, file too large')
            return 
        data = self.rfile.read(size)
        sync_id, file, data = data.split('\r\n', 2)
        
        remote_file = self.get_remote_file(sync_id, file)
        if remote_file is None:
            self.wfile.write('DENY, id not registered')
            return
        
        LOG.info('recv %d bytes for %s from %s' % 
                 (len(data), remote_file, str(self.client_address)))
        
        local_file = self.write_local_file(data)
        
        username = remote_file.split('@', 1)[0]
        password = parse_config.get_user_password(username)
        
        message = self.sync(local_file, remote_file, password)
        
        LOG.info("send %s to %s" % (message, str(self.client_address)))
        
        self.wfile.write(message)
        
    def get_remote_file(self, sync_id, file):
        remote_dir = parse_config.get_remote_dir(sync_id)
        if remote_dir:
            return os.path.join(remote_dir, file)
        
    def sync(self, local_file, remote_file, password):
        message = 'OK'
        try: 
            prompt = sync_file.sync(local_file, remote_file, password)
            if prompt and prompt.find('100%') != -1:
                message = 'OK'
            else:
                LOG.error(prompt)
                message = 'FAIL, your remote host not in ssh2 hostkeys?'
        except Exception, e: 
            LOG.error(str(e))
            message = 'FAIL, %s' % str(e)
        os.remove(local_file)
        return message
        
    def write_local_file(self, data):
        host, port = self.client_address
        tmpfile = '_'.join([host, str(port)])        
        try:
            fp = open(tmpfile, 'w')            
            fp.write(data)
        finally:
            fp.close()
        return tmpfile        

class MyTCPServer(SocketServer.ThreadingTCPServer):
    allow_reuse_address = True
    

if __name__ == "__main__":
    main_dir = os.path.dirname(os.path.abspath(__file__))
    os.chdir(main_dir)
    
    logging.config.fileConfig('logging.conf')
    LOG = logging.getLogger('sync')    
    
    bind_address = parse_config.get_bind_address()
    LOG.info('try to listen %s' % str(bind_address))
    server = SocketServer.ThreadingTCPServer(bind_address, MyTCPHandler)
    server.serve_forever()
